import React, { createRef, PureComponent } from 'react'
import { connect } from '@umijs/max'
import { Button, Form, Input, message, Modal, Radio, Select, TreeSelect } from 'antd'
import { ExclamationCircleOutlined } from '@ant-design/icons'
import { DispatchConf, OperateRecord, ViewDetail } from './page-components'
import { regExp } from '@/utils/regExp.js'
import Tools from '@/utils/Tools'
import styles from './index.less'
import { flinkLockNode, flinkPublish, getListAll, getTaskDetail, getTree, saveFlinkTaskNode } from '../api'

const Bus = Tools.Bus
const { Option } = Select
const { TextArea } = Input

@connect(({ realTimeScriptDev }) => ({ ...realTimeScriptDev }))
export default class Flink extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      scheduleStatus: 0,
      selectedBtn: null,
      edit: false,
    }
    this.viewDetailRef = createRef()
    this.operateRecordRef = createRef()
    this.dispatchConfRef = createRef()
    this.procedureForm = React.createRef()
  }

  componentDidMount() {
    this.getDirTree()
    this.getTaskDetail()
    this.getResourceListAll()
  }

  componentWillUnmount() {
  }

  // eslint-disable-next-line react/no-unused-class-component-methods
  toggleViewDetail = () => {
    this.operateRecordRef && this.operateRecordRef?.current?.toggleOperateRecord(false)
    this.dispatchConfRef && this.dispatchConfRef?.current?.toggleDispatchConf(false)
    this.viewDetailRef && this.viewDetailRef?.current?.toggleViewDetail()
    this.setState({
      selectedBtn: 'detail',
    })
  };

  toggleOperateRecord = () => {
    this.dispatchConfRef && this.dispatchConfRef?.current?.toggleDispatchConf(false)
    this.viewDetailRef && this.viewDetailRef?.current?.toggleViewDetail(false)
    this.operateRecordRef && this.operateRecordRef?.current?.toggleOperateRecord()
    this.setState({
      selectedBtn: 'record',
    })
  }

  toggleDispatchConf = () => {
    this.viewDetailRef && this.viewDetailRef?.current?.toggleViewDetail(false)
    this.operateRecordRef && this.operateRecordRef?.current?.toggleOperateRecord(false)
    this.dispatchConfRef && this.dispatchConfRef?.current?.toggleDispatchConf()
    this.setState({
      selectedBtn: 'conf',
    })
  }

  // 发布and取消发布
  flinkPublish = (isPublished) => {
    const { taskNode } = this.props
    this.setState({
      lodings: true,
    })
    flinkPublish({ id: taskNode.nodeId, isPublished }).then((res) => {
      if (res.status === 200) {
        this.getTaskDetail()
        message.success(res.msg)
      } else {
        message.error(res.msg)
      }
      this.setState({
        lodings: false,
      })
    })
  }

  // 任务详情
  getTaskDetail = () => {
    const { taskNode } = this.props
    const { nodeId } = taskNode || {}
    const params = {
      nodeId,
    }
    getTaskDetail(params).then((res) => {
      if (res.status === 200) {
        this.setState({
          taskDetail: res.data || '',
          scheduleStatus: res.data.isPublished || 0,
          isLocked: res.data.isLocked,
        })
        this.procedureForm?.current?.setFieldsValue({
          pid: res.data.pid == '1' ? undefined : res.data.pid,
          devType: 1,
          name: res.data.name,
          resourceNodeId: res.data.resourceNodeId,
          mainClass: res.data.mainClass,
          remark: res.data.remark,
          nodeType: res.data.nodeType,
        })
      }
    })
  }

  // 锁定解锁
  flinkLockNode = (isLocked) => {
    const { taskNode } = this.props
    const { nodeId } = taskNode || {}
    flinkLockNode({ id: nodeId, isLocked }).then((res) => {
      if (res.status === 200) {
        message.success(res.msg)
        this.setState({
          isLocked,
        })
      } else {
        message.error(res.msg)
      }
    })
  }

  getResourceListAll = () => {
    getListAll({ type: 1 }).then((res) => {
      if (res.status === 200) {
        this.setState({
          resources: res.data,
        })
      }
    })
  }

  getDirTree = () => {
    getTree({ type: 0 }).then((res) => {
      if (res.data && res.data[0]) {
        const { childs } = res.data[0]
        this.setState({
          dirTree: childs,
        })
      } else {
        this.setState({
          dirTree: [],
        })
      }
    })
  }

  confirm = () => {
    Modal.confirm({
      title: '提交',
      icon: <ExclamationCircleOutlined />,
      content: '文件被修改，是否要保存？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        this.fileTaskFlow()
      },
    })
  };

  fileTaskFlow = () => {
    const { taskNode } = this.props
    const { nodeId } = taskNode || {}
    this.procedureForm.current.validateFields().then(values => {
      const postObj = {
        ...values,
        pid: values.pid ? values.pid : 1,
        nodeId,
        devType: 1,
      }
      saveFlinkTaskNode(postObj).then((res) => {
        if (res.status === 200) {
          this.props.dispatch({
            type: 'realTimeScriptDev/getTree',
            params: { type: 0 },
          })
          this.setState({
            edit: false,
          })
          message.success(res.msg)
        } else {
          message.error(res.msg)
        }
      })
    })
  }

  valuesChange = (value, allValues) => {
    this.setState({
      edit: true,
    })
  }

  render() {
    const { taskNode } = this.props
    const {
      selectedBtn, taskDetail, edit, resources, isLocked,
    } = this.state
    const descRe = regExp.proName(0, 128)
    return (
      <div className={styles.flink_container}>
        <div className={styles.flink_panel_header}>
          <dl onClick={() => {
            this.fileTaskFlow()
          }}
          >
            <dt><i className="iconfont_new iconbaocun" /></dt>
            <dd>保存</dd>
          </dl>
          {isLocked ? (
            <dl onClick={() => {
              this.flinkLockNode(0)
            }}
            >
              <dt><i className="iconfont_new iconsuo" /></dt>
              <dd>解锁</dd>
            </dl>
          ) : (
            <dl onClick={() => {
              this.flinkLockNode(1)
            }}
            >
              <dt><i className="iconfont_new iconsuo" /></dt>
              <dd>锁定</dd>
            </dl>
          )}
          <span className={styles.flink_panel_button} style={{ float: 'right' }}>
            {this.state.scheduleStatus == 0 ? (
              <Button
                loading={this.state.lodings}
                onClick={() => {
                  if (edit) {
                    this.confirm()
                  } else {
                    this.flinkPublish(1)
                  }
                }}
              >发布
              </Button>
            ) : (
              <Button
                loading={this.state.lodings}
                onClick={() => {
                  this.flinkPublish(0)
                }}
              >取消发布
              </Button>
            )}
            <Button
              type="primary"
              style={{ marginLeft: '.16rem' }}
              onClick={() => {
                window.location = `${window.suanpan}#/data-development/realTime/task-operation`
              }}
            >运维
            </Button>
          </span>
        </div>
        <div className={styles.flink_editor}>
          <div className={styles.flink_editor_box}>
            <div className={styles.flink_editor_left}>
              <div className={styles.flink_editor_center}>
                <Form
                  labelCol={{ span: 5 }}
                  wrapperCol={{ span: 19 }}
                  autoComplete="off"
                  ref={this.procedureForm}
                  onValuesChange={this.valuesChange}
                >
                  <Form.Item
                    label="任务名称"
                    name="name"
                    rules={[
                      { required: true, message: '请输入任务名称' },
                      {
                        required: false,
                        pattern: new RegExp(regExp.name(2, 64).reg, 'g'),
                        message: regExp.name(2, 64).text,
                      },
                    ]}
                  >
                    <Input placeholder="请输入工作流程名称" />
                  </Form.Item>
                  <Form.Item
                    label="任务类型"
                    name="nodeType"
                    rules={[
                      { required: true, message: '请选择任务类型' },
                    ]}
                  >
                    <Radio.Group disabled>
                      <Radio value={1}>FlinkSQL</Radio>
                      <Radio value={3}>Flink</Radio>
                    </Radio.Group>
                  </Form.Item>
                  <Form.Item
                    label="资源"
                    name="resourceNodeId"
                    rules={[
                      { required: true, message: '请选择资源' },
                    ]}
                  >
                    <Select placeholder="请选择资源">
                      {resources && resources.map((item) => <Option key={item.id} value={item.id}>{item.name}</Option>)}
                    </Select>
                  </Form.Item>
                  <Form.Item
                    label="mainClass"
                    name="mainClass"
                    rules={[
                      { required: true, message: '请输入mainClass' },
                    ]}
                  >
                    <Input placeholder="请输入mainClass" />
                  </Form.Item>
                  <Form.Item
                    label="父级目录"
                    name="pid"
                  >
                    <TreeSelect
                      treeData={this.state.dirTree || []}
                      dropdownStyle={{ maxHeight: '4rem', overflow: 'auto' }}
                      placeholder="选择父级目录"
                      allowClear
                      fieldNames={
                        {
                          label: 'name',
                          value: 'id',
                          children: 'childs',
                        }
                      }
                      filterTreeNode={(input, treeNode) => treeNode.name.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                      showSearch
                      treeDefaultExpandAll
                    />
                  </Form.Item>
                  <Form.Item
                    label="描述"
                    name="remark"
                    rules={[
                      { required: false },
                      {
                        pattern: new RegExp(descRe.reg, 'g'),
                        message: descRe.text,
                      },
                    ]}
                  >
                    <TextArea
                      placeholder="请输入实时计算的业务描述"
                      autoSize={{ minRows: 3, maxRows: 6 }}
                    />
                  </Form.Item>
                </Form>
              </div>
            </div>
            <div className={styles.flink_right}>
              <span className={`${styles.flink_right_span} ${selectedBtn === 'detail' ? styles.on : ''}`} onClick={this.toggleViewDetail}>任务详情</span>
              <span className={`${styles.flink_right_span} ${selectedBtn === 'record' ? styles.on : ''}`} onClick={this.toggleOperateRecord}>环境参数</span>
              <span className={`${styles.flink_right_span} ${selectedBtn === 'conf' ? styles.on : ''}`} onClick={this.toggleDispatchConf}>调度配置</span>
              <ViewDetail ref={this.viewDetailRef} taskDetail={taskDetail} />
              <DispatchConf ref={this.dispatchConfRef} taskNode={taskNode} detailTaskFlow={this.detailTaskFlow} />
              <OperateRecord ref={this.operateRecordRef} taskNode={taskNode} />
            </div>
          </div>
          {isLocked ? <div className={styles.flink_isLocked} /> : null}
        </div>
      </div>
    )
  }
}
